package com.hw.utils;



import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Vector;

public class HttpDownload {
    private static int BUFFER_SIZE = 8096; // 缓冲区大小  
  
    /** 
     * 　* 构造方法 　 
     */  
    public HttpDownload() {  
    }  

  
    /** 
     * 将HTTP资源另存为文件 
     *  
     * @param destUrl 
     *            String 
     * @param fileName 
     *            String 
     * @throws Exception 
     */  
    public static void saveToFile(String destUrl, String fileName) throws IOException {  
        FileOutputStream fos = null;  
        BufferedInputStream bis = null;  
        HttpURLConnection httpUrl = null;  
        URL url = null;  
        byte[] buf = new byte[BUFFER_SIZE];  
        int size = 0;  
        // 建立链接  
        url = new URL(destUrl);  
        httpUrl = (HttpURLConnection) url.openConnection();  
        // 连接指定的资源  
        httpUrl.connect();  
        // 获取网络输入流  
        bis = new BufferedInputStream(httpUrl.getInputStream());  
        // 建立文件  
        fos = new FileOutputStream(fileName);  
        // 保存文件  
        while ((size = bis.read(buf)) != -1)  
            fos.write(buf, 0, size);  
        fos.close();  
        bis.close();  
        httpUrl.disconnect();  
    }  
    
    public static InputStream saveToFile2(String destUrl, String fileName) throws IOException {  
        HttpURLConnection httpUrl = null;  
        URL url = null;  
        // 建立链接  
        url = new URL(destUrl);  
        httpUrl = (HttpURLConnection) url.openConnection();  
        // 连接指定的资源  
        httpUrl.connect();  
        // 获取网络输入流 
        InputStream iis= httpUrl.getInputStream();
        return iis;
    }  

  
    /** 
     * 主方法(用于测试) 
     *  
     * @param argv 
     *            String[] 
     */  
//    public static void main(String argv[]) {  
//    	HttpDownload oInstance = new HttpDownload();  
//        try {  
//            oInstance.saveToFile("http://192.168.1.52/20150625/MP4/FILE0008.MP4",  
//                    "F://11111111111111111111111111111111.MP4");  
//        } catch (Exception err) {  
//            System.out.println(err.getMessage());  
//        }  
//    }  
}  
